import { Commit, createStore } from "vuex";
import axios, { AxiosRequestConfig } from "axios";
//封装 get 请求
const getAndCommit = async (
  url: string,
  mutationName: string,
  commit: Commit
) => {
  const { data } = await axios.get(url);
  commit(mutationName, data);
};
//封装 post 请求
const postAndCommit = async (
  url: string,
  mutationName: string,
  commit: Commit,
  payload: any
) => {
  const { data } = await axios.post(url, payload);
  commit(mutationName, data);
};

const asyncAndCommit = async (url: string, mutationName: string, commit: Commit, config: AxiosRequestConfig = { method: 'get'}) => {
  const { data } = await axios(url, config)
  commit(mutationName, data)
  return data
}

//作者信息
export interface UserProps { //当前是否登录
  isLogin: boolean;
  nickName?: string;
  _id?: string;
  column?: string;
  avatar?: ImageProps;
  description?: string
}

export interface ImageProps {
  _id?: string;
  url?: string;
  createdAt?: string;
}

export interface ColmunProps { 
  //专栏列表
  _id: string;
  title: string; //标题
  avatar?: ImageProps; //头像
  description: string; //描述
}

export interface PostProps {
  //文章列表
  _id?: string;
  title: string;
  excerpt?: string;
  content?: string; //内容
  image?: ImageProps | string; //图片
  createdAt?: string; //发布时间
  column: string; //文章id
  author?: string | UserProps
}

//声明错误
export interface GlobalErrorProps {
  status: boolean;
  message?: string;
}
//上传
export interface ResponseType<P = []> {
  code: number;
  msg: string;
  data: P;//上传的内容
}

//如果要在其他页面使用，需要导出
export interface GolbalDataProps {
  colmuns: ColmunProps[];
  posts: PostProps[];
  user: UserProps;
  loading: boolean;
  token: string;
  error: GlobalErrorProps;
}

const store = createStore<GolbalDataProps>({
  state: {
    colmuns: [],
    posts: [],
    user: { isLogin: false },
    loading: false,
    token: localStorage.getItem("token") || "",
    error: { status: false },
  },
  getters: {
    //专栏详情
    getColmunById: (state) => (id: string) => {
      return state.colmuns.find((c) => c._id === id);
    },
    //文章列表
    getPostById: (state) => (cid: string) => {
      return state.posts.filter((post) => post.column === cid);
      // return state.posts[0].colmun === cid
    },
    //文章详情
    getCurrentPost: (state) => (id: number) => {
      return state.posts[id]
    }
  },
  mutations: {
    //登录
    login(state, rwaData) {
      const { token } = rwaData.data;
      state.token = token;
      localStorage.setItem("token", token);
      axios.defaults.headers.common.Authorization = `Bearer ${token}`;
      // state.user = { ...state.user, isLogin: true, name: '鲲'}
    },
    logout(state) {
      state.token = "";
      localStorage.removeItem("token");
      delete axios.defaults.headers.common.Authorization;
    },
    //获取用户信息
    fetchCurrentUser(state, rwaData) {
      state.user = { isLogin: true, ...rwaData.data };
    },
    //新建文章
    createPost(state, newPost) {
      state.posts.push(newPost);
    },
    //专栏列表
    fetchColmuns(state, rwaData) {
      state.colmuns = rwaData.data.list;
    },
    //专栏详情
    fetchColmun(state, rwaData) {
      state.colmuns = [rwaData.data];
    },
    //文章列表
    fetchPosts(state, rwaData) {
      state.posts = rwaData.data.list;
      console.log(state.posts);
    },
    //文章详情
    fetchPost (state, rwaData) {
      state.posts[rwaData.data._id] = rwaData.data
    },
    //更新文章
    updatePost (state, { data }) {
      // state.posts[data._id] = data
      state.posts = state.posts.map(post => {
        if(post._id === data._id) {
          return data
        } else {
          return post
        }
      })
    },
    //删除文章
    deletePost (state, { data }) {
      state.posts = state.posts.filter(post => post._id !== data.id)
    },
    //控制 loading 效果显示隐藏
    setLoading(state, status) {
      state.loading = status;
    },
    //消息错误提示
    setError(state, e: GlobalErrorProps) {
      state.error = e;
    },
  },
  actions: {
    //专栏列表
    async fetchColmuns(context) {
      // axios.get('/columns').then(resp => {
      //   context.commit('fetchColmuns', resp.data)
      // })
      getAndCommit("/columns", "fetchColmuns", context.commit);
    },
    //专栏详情
    async fetchColmun({ commit }, cid) {
      // axios.get(`/columns/${cid}`).then(resp => {
      //   commit('fetchColmun', resp.data)
      // })
      getAndCommit(`/columns/${cid}`, "fetchColmun", commit);
    },
    //文章列表
    async fetchPosts({ commit }, cid) {
      // axios.get(`/columns/${cid}/posts`).then(resp => {
      //   commit('fetchPosts', resp.data)
      //   console.log(resp.data);

      // })
      getAndCommit(`/columns/${cid}/posts`, "fetchPosts", commit);
    },
    //文章详情
    fetchPost ({ state, commit }, id) {
      const currentPost = state.posts[id]
      if(!currentPost || !currentPost.content) {
        return getAndCommit(`/posts/${id}`,'fetchPost',commit)
      } else {
        return Promise.resolve({ data: currentPost })
      }
    },
    //更新文章
    updatePost ({ commit }, { id, payload }) {
      return asyncAndCommit(`/posts/${id}`, 'updatePost', commit, {
        method:'patch',
        data: payload
      })
    },
    //删除文章
    deletePost ({ commit }, id) {
      return asyncAndCommit(`/posts/${id}`,'deletePost',commit, { method: 'delete' })
    },
    //登录
    login({ commit }, payload) {
      return postAndCommit("/user/login", "login", commit, payload);
    },
    //获取用户信息
    fetchCurrentUser({ commit }) {
      getAndCommit("/user/current", "fetchCurrentUser", commit);
    },
    loginAndFecth({ dispatch }, loginData) {
      return dispatch("login", loginData).then(() => {
        return dispatch("fetchCurrentUser");
      });
    },
    //新建文章
    createPost ({ commit }, payload) {
      return postAndCommit('/posts', 'createPost', commit, payload)
    }
  },
  modules: {},
});
export default store;
